package com.jialiang.base.admin.account.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jialiang.base.admin.account.domain.service.IUserRoleService;
import com.jialiang.base.admin.account.domain.mapper.RoleMapper;
import com.jialiang.base.admin.account.domain.mapper.UserMapper;
import com.jialiang.base.admin.account.domain.mapper.UserRoleMapper;
import com.jialiang.base.admin.account.domain.pojo.entity.Role;
import com.jialiang.base.admin.account.domain.pojo.entity.User;
import com.jialiang.base.admin.account.domain.pojo.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author jialiang
* @description 针对表【account_user_role(用户角色关联)】的数据库操作Service实现
* @createDate 2024-09-26 18:40:06
*/
@Service
public class IUserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements IUserRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public List<Role> listRolesIdByUserId(Long id) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        if (userRoles.isEmpty()){
            return Collections.emptyList();
        }
        Set<Long> rolesId = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        return roleMapper.selectBatchIds(rolesId);
    }

    @Override
    public List<User> listUsersByRoleId(Long id) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",id);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        if (userRoles.isEmpty()){
            return Collections.emptyList();
        }
        Set<Long> userId = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toSet());
        return userMapper.selectBatchIds(userId);
    }
}




